import jwt
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.conf import settings
from .. import return_code


class CurrentUser(object):
    def __init__(self, user_id, username, exp):
        self.user_id = user_id
        self.username = username
        self.exp = exp


class MtbAuthenticationFailed(AuthenticationFailed):
    status_code = 200


class JwtTokenAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # token = request.query_params.get('token')
        token = request.META.get('HTTP_AUTHORIZATION')
        # print(token)
        if not token:
            raise MtbAuthenticationFailed({"code": return_code.AUTH_FAILED, "error": "认证失败"})
        try:
            payload = jwt.decode(token, settings.SECRET_KEY, ["HS256"])
            # print(payload)
            return CurrentUser(**payload), token
        except Exception as e:
            raise MtbAuthenticationFailed({"code": return_code.AUTH_FAILED, "error": "认证失败"})

    def authenticate_header(self, request):
        return 'Bearer realm="API"'
